package com.shen.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shen.server.config.sencurity.component.JwtTokenUtils;
import com.shen.server.mapper.RoleMapper;
import com.shen.server.pojo.Admin;
import com.shen.server.mapper.AdminMapper;
import com.shen.server.pojo.RespBean;
import com.shen.server.pojo.Role;
import com.shen.server.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HMF
 * @since 2022-04-10
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Resource  // 这里报红可以不用管 或 换成 @Resource
    private AdminMapper adminMapper;

    @Autowired
    private UserDetailsService userDetailsService;  // 注入Spring Security里的类

    @Autowired // 这里报红就需要处理了
    private PasswordEncoder passwordEncoder; // Spring Security提供的专门加密密码的工具

    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Value ("${jwt.tokenHead}")
    private String tokenHead; // 从配置文件中获取token的头部信息

    @Resource
    private RoleMapper roleMapper;
    /**
     * 登录之后返回 token 实现方法
     *
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        //验证验证码  
        String captcha = (String)request.getSession().getAttribute("captcha");
        if(StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码错误，请重新输入！");
        }
        // 登录
        // 通过Spring Security里面的UserDetailsService的loadUserByUsername()方法实现登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确！");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号被禁用，请联系管理员！");
        }

        // 更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //【把登录的用户对象放到SpringSecurity全局中】
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 如果前面的判断都通过了，就拿到一个令牌 token
        String token = jwtTokenUtils.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead); // 这个是给前端，让她们放到请求头中的

        return RespBean.success("登录成功", tokenMap);
    }

    /**
     * 根据用户名username获取完整的用户对象 实现方法
     *
     * @param username
     * @return
     */
    public Admin getAdminByUserName(String username) {
        // 因为使用了MyBatisPlus，所以查询数据就变的更简单了
        return adminMapper.selectOne(new QueryWrapper<Admin>()
                // 可以使用链式编程，一直...eq()方法
                .eq("username", username)
                .eq("enabled", true));
    }

    //根据用户id查询用户角色列表
    @Override
    public List<Role> getRolesByAdminId(Integer adminId) {
        return roleMapper.getRolesByAdminId(adminId);
    }

    /**
     * 获取所有的操作员
     * @date: 2022/4/19
     * @param: keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        Integer id = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        return adminMapper.getAllAdmins(id,keywords);
    }

    /**
     * 更新用户密码
    * @date: 2022/4/24
    * @param: oldPass
    * @param: pass
    * @param: adminId
    * @return
    */

    @Override
    public RespBean updateAdminPwd(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(encoder.encode(pass));
            int result = adminMapper.updateById(admin);
            if (1==result){
                return RespBean.success("更新成功！");
            }
        }
        return RespBean.error("更新失败！");
    }

    /**
     * 更新用户头像
    * @date: 2022/4/25
    * @param: url
    * @param: id
    * @param: authentication
    * @return
    */

    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {

        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);
        int result = adminMapper.updateById(admin);
        if (1 == result){
            Admin principal = (Admin)authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().
                    setAuthentication(new UsernamePasswordAuthenticationToken
                            (admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功！",url);
        }

        return RespBean.error("更新失败！");
    }


}


